# -*- coding: utf-8 -*-
"""
-------------------------------------------------
   File Name：     Project -> KamWebApi
   Description :   可爱猫对接接口API
   Author :        William
   date：          2020/2/21/0021
-------------------------------------------------
   Change Activity:
                   2020/2/21/0021: 可爱猫对接接口API文件初创
                   2020/2/26：修改一对多微信推送接口
-------------------------------------------------
"""
import requests
import base64
from Config.Setting import *

class KamWeb:
    def __init__(self):
        self.Send_Url = Send_Url

    def send_request(self,data):
        '''通用消息发送接口 get请求，需要把请求的参数以dict的格式组合发送过来'''
        try:
            url = self.Send_Url.get(data["robwxid"],"空")
            if url:
                res = requests.get(url, params=data)
                logger.info(res.text)
                return True
            else:
                logger.info(f"请检查多微信通讯地址是否正确{url}")
        except Exception as e:
            logger.warning(f"{e},请检查当前地址是否可用！{self.Send_Url}")
            return False

    def bs64_url_data_encode(self,st):
        '''进行文本编码 url 编码 -> Bs64 编码'''
        from urllib.parse import quote, unquote
        new_str = str(st)
        new_str = unquote(new_str)
        encode_str = base64.b64encode(new_str.encode()).decode("utf-8")
        return encode_str

    def send_text_msg(self,robwxid,to_wxid,msg):
        '''私聊文本消息发送 事件接口位置： Id:10001 -> Type:10001'''
        data = {}
        data["robwxid"] = robwxid
        data["Id"] = self.bs64_url_data_encode(10001)
        data["Type"] = self.bs64_url_data_encode(10001)
        data["robot_wxid"] = self.bs64_url_data_encode(robwxid)
        data["to_wxid"] = self.bs64_url_data_encode(to_wxid)
        data["msg"] = self.bs64_url_data_encode(msg)
        return self.send_request(data)

    def send_group_at_msg(self,robwxid, group_wxid, at_wxid, at_name, msg):
        '''群发消息 事件接口位置：Id:10003 -> Type:20001 '''
        data = {}
        data["robwxid"] = robwxid
        data["Id"] = self.bs64_url_data_encode(10003)
        data["Type"] = self.bs64_url_data_encode(20001)
        data["robot_wxid"] = self.bs64_url_data_encode(robwxid)
        data["group_wxid"] = self.bs64_url_data_encode(group_wxid)
        data["member_wxid"] = self.bs64_url_data_encode(at_wxid)
        data["member_name"] = self.bs64_url_data_encode(at_name)
        data["msg"] = self.bs64_url_data_encode(msg)
        return self.send_request(data)

kamweb = KamWeb()
